<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\UserRole;
use App\Models\Project;
use App\Models\UserAuthMenus;
use App\Models\UserMenus;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Facades\Validator;

class   AuthController extends Controller
{
    /**
     * Create a new AuthController instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth:api', ['except' => ['login']]);
    }

    /**
     * Get a JWT via given credentials.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
        $validate = Validator::make($request->all(), [
            'js_code' => 'required',
        ], [
            'js_code.required' => 'js_code不能为空！',
        ]);

        if ($validate->fails()) {
            return showError($validate->errors()->first());
        }

        $params = $validate->getData();
        $appid = env('APP_ID', 'wxd4b08d6d8252ddc2');
        $secret = env('APP_SECRET', '197bf375a8d3a09543c8f939b4953c40');
        $js_code = $params['js_code'];
        $grant_type = 'authorization_code';

        $data = [
            'appid' => $appid,
            'secret' => $secret,
            'js_code' => $js_code,
            'grant_type' => $grant_type,
        ];

        $ym = env('WX_URL', 'https://api.weixin.qq.com');
        $url = $ym . "/sns/jscode2session";
        $res = json_decode(curlRequest($url, $data), true);

        if (!isset($res['openid'])) {
            return showError('登录失败');
        }
        // $res['openid']=11111;
        $user = User::query()->where('openid', $res['openid'])->first();
        if (!$user) {
            $li['openid'] = $res['openid'];
            $user = User::query()->create($li);
        }

        $token = JWTAuth::fromUser($user);
        return $this->respondWithToken($token);
    }

    /**
     * Log the user out (Invalidate the token).
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        auth('api')->logout();

        return showSuccess('退出成功');
    }

    /**
     * Refresh a token.
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return $this->respondWithToken(auth('api')->refresh());
    }

    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth('api')->factory()->getTTL() * 60
        ]);
    }

    /**
     * Get the authenticated User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function apiInfo(Request $request)
    {
        try {
            $data=auth('api')->user();
            if($data['now_role_id']){
                $role=UserRole::query()->where('id',$data['now_role_id'])->first();
                $data['now_role_str']=$role->name;
            }else{
                $data['now_role_str']='';
            }
            if($data['project_id']){
                $project=Project::query()->where('id',$data['project_id'])->first();
                $data['project_str']=$project->name;
            }else{
                $data['project_str']='';
            }
            if($data['user_role_ids']){
                $role_arr=UserRole::query()->select('id','name')->whereIn('id',explode(',',$data['user_role_ids']))->get();
                $data['user_role_arr']=$role_arr;
            }else{
                $data['user_role_arr']=[];
            }
            return showData($data);
        } catch (\Exception $e) {
            return showError('获取失败');
        }
        
    }

    // 更新用户信息
    public function updateInfo(Request $request)
    {
        $params = $request->all();
        try {
            $find=User::query()->where('id',auth('api')->user()->id)->first()->toArray();
            $Info['nickname']=$params['nickname']??$find['nickname'];
            $Info['avatar_url']=$params['avatar_url']??$find['avatar_url'];
            $Info['username']=$params['username']??$find['username'];
            $Info['phone']=$params['phone']??$find['phone'];
            $phone_id=User::query()->where('phone',$params['phone'])->value('id');
            if($phone_id&&$phone_id!=auth('api')->user()->id){
                return showError('此手机号已被注册');
            }
            $Info['user_role_ids']=$params['user_role_ids']??$find['user_role_ids'];
            $Info['now_role_id']=$params['now_role_id']??$find['now_role_id'];
            if(!empty($Info['user_role_ids'])&&empty($Info['now_role_id'])){
                $Info['now_role_id']=explode(',',$Info['user_role_ids'])[0];
            }
            $Info['user_auth_id']=$params['user_auth_id']??$find['user_auth_id'];
            $Info['village_id']=$params['village_id']??$find['village_id'];
            $Info['grid_group_id']=$params['grid_group_id']??$find['grid_group_id'];
            $Info['segment_id']=$params['segment_id']??$find['segment_id'];
            $Info['id_obverse_img']=$params['id_obverse_img']??$find['id_obverse_img'];
            $Info['id_reverse_img']=$params['id_reverse_img']??$find['id_reverse_img'];
            $Info['signatures_img']=$params['signatures_img']??$find['signatures_img'];
            $Info['apply_img']=$params['apply_img']??$find['apply_img'];
            $Info['street_id']=$params['street_id']??$find['street_id'];
            $Info['project_id']=$params['project_id']??$find['project_id'];
            if(isset($params['id_obverse_img'])||isset($params['id_reverse_img'])){
                $Info['apply_status']=1;
            }
            $add=User::query()->where('id',auth('api')->user()->id)->update($Info);
            return showSuccess('更新成功！');
        } catch (\Exception $e) {
            return showError($e->getMessage());
        }
        
    }

    // 获取用户权限
    public function authInfo(Request $request)
    {
        try {
            $menus_auth_id=auth('api')->user()->menus_auth_id??1;
            $menus_ids = UserAuthMenus::query()->where('auth_id',$menus_auth_id)->value('menus_ids');
            $data = UserMenus::query()
            ->whereIn('id',explode(',',$menus_ids))
            ->where('pid','<>',0)
            ->pluck('slug')->toArray();

            return showData($data);
        } catch (\Exception $e) {
            return showError('获取失败');
        }
        
    }
}
